package org.opens.filters;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 说明:
 * <pre>
 *     1. 这是一个自定义鉴权全局过滤器;
 * </pre>
 */
//@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 说明:
     * <pre>
     *     1. 这个方法用来写过滤器逻辑;
     * </pre>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (!StringUtils.equals("admin", token)) {
            log.info("认证失败");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 说明:
     * <pre>
     *     1. 用来描述过滤器的优先级, 值越小则优先级越高;
     * </pre>
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
